﻿using CoreShop.App.Member;
using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.UI;
using CoreShop.Services;
using FastMember;
using Loading;
using Newtonsoft.Json;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;

namespace CoreShop.App
{
    public partial class FrmUserGetInfo : BaseForm
    {
        OpaqueCommand cmd = new OpaqueCommand();
        public corecmsuser member = null;
        public corecmsuser oldMember = null;
        public FrmUserGetInfo(corecmsuser _member,string number = "")
        {
            InitializeComponent();
            member = _member;
            oldMember = _member;
            this.txtSendKey.Text = number;
            this.numPad.FillColor = Color.White;
            txtSendKey.TextBox.GotFocus += txtSendKey_GotFocus;
        }

        private void txtSendKey_GotFocus(object sender, System.EventArgs e)
        {
            numPad.SetTextBox((UIEdit)sender, UITextBox.UIEditType.String, 0);
        }

        private void FrmEditInputs_Load(object sender, EventArgs e)
        {
            SetMemberInfo();
            //ControlsDataBinding.DataBind(member, this, DataSourceUpdateMode.Never);
            //ksKeyBoard1.InputControl = txtSendKey;
        }

        private void SetMemberInfo()
        {
            this.Invoke(new Action(() =>
            {
                lbl_balance.Text = "0.00";
                lbl_points.Text = "0";
                btnSendCard.Visible = false;
                foreach (Control ctr in this.FindForm().Controls)
                {
                    if (ctr is Label)
                    {
                        Label lb = ctr as Label;
                        if (CommFunc.ConvertToString(lb.Tag) == "field")
                        {
                            lb.Text = "";
                        }
                    }
                }
                if ((member != null) && (member.id > 0))
                {
                    lbl_balance.Text = member.balance.ToString();
                    lblGiftAmount.Text = member.giftBalance.ToString();
                    lbl_points.Text = CommFunc.ConvertToInt32(member.point).ToString();                    
                    ControlsDataBinding.ValueBind(member, this);
                    discountValue.Text = member.discountValue.ToString("#");
                    status.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.MemberStatus>(member.status ?? 1);
                    grade.Text = member.gradeName;
                    //if (string.IsNullOrEmpty(member.cardId)) btnSendCard.Visible = true;                    
                    if (member.storeId == AppConstVars.sysStore.id)
                    {
                        corecmsusercategory memberCategory = new corecmsusercategoryServices().GetById(member.userCategoryId);
                        if (memberCategory != null) userCategoryId.Text = memberCategory.name;
                        corecmsusergrade memberGrade = new corecmsusergradeServices().GetById(member.grade);
                        grade.Text = member.gradeName;
                    }
                    txtSendKey.Text = mobile.Text;
                    status.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.MemberStatus>(member.status.ObjToInt(0));
                    txtSendKey.Focus();
                    txtSendKey.SelectAll();
                }
            }));            
        }


        private void btnOK_Click(object sender, EventArgs e)
        {
            //bool check = CheckData1();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

        }

        private void txtSendKey_TextChanged(object sender, EventArgs e)
        {
            //txtSendKey.ShowButton = !string.IsNullOrEmpty(this.txtSendKey.Text);
        }

        private void txtSendKey_ButtonClick(object sender, EventArgs e)
        {
            txtSendKey.Text = "";
            txtSendKey.Focus();
        }
                        
        private async void GetMemberInfo(string sNumber, int type)
        {
            if (txtSendKey.Text == "")
            {
                UIMessageBox.Show("请输入要查询的会员", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                member = await MemberApiUtil.GetListVipInfo(sNumber);
                if ((member == null) || (member.id == 0)) return;

                if (member.storeId != AppConstVars.sysStore.id)
                {
                    this.Invoke(new Action(() =>
                    {
                        btn_EditMember.Enabled = false;
                        password.Enabled = false;
                    }));
                }
                SetMemberInfo();

                if (type == 1) 
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch { }
            finally {
                cmd.HideOpaqueLayer();
            }            
        }

        private void txtSendKey_KeyDown(object sender, KeyEventArgs e)
        {
            int mkeycode = e.KeyValue;
            if (mkeycode == 13)
            {
                this.btnRead_Click(null, null);
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            GetMemberInfo(txtSendKey.Text, 0);
        }

        private void FrmMemberGetInfo_Shown(object sender, EventArgs e)
        {
            txtSendKey.Focus();
            txtSendKey.SelectAll();
            if (!string.IsNullOrEmpty(txtSendKey.Text))
            {
                btnRead_Click(null, null);
            }
        }

        private async Task ReloadMemberAsync()
        {
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                if ((member != null) && (member.id > 0))
                {
                    member = await MemberApiUtil.GetListVipInfo(member.mobile.ToString());
                    if (member != null)
                    {
                        SetMemberInfo();
                    }
                }
            }
            catch { }
            finally {
                cmd.HideOpaqueLayer();
            }
        }

        private async void btnMemberDeposit_Click(object sender, EventArgs e)
        {            
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isUserDeposit, 0)) return;
            new MemberUtil().SetUserDeposit(member);
            await ReloadMemberAsync();
            txtSendKey.Focus();
        }


        private async void btn_AddMember_ClickAsync(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isAddUserInfo, 0)) return;
            FrmUserRegister frmUserRegister = new FrmUserRegister(txtSendKey.Text);
            //frm.Render();
            if (frmUserRegister.ShowDialog() == DialogResult.OK)
            {
                member = frmUserRegister.member;
                await ReloadMemberAsync();
                //SetMemberInfo();
            }
            frmUserRegister.Dispose();
        }

        private void btn_EditMember_Click(object sender, EventArgs e)
        {
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择会员，不能修改。");
                return;
            }
            FrmUserEdit frm = new FrmUserEdit(member);
            if (frm.ShowDialog() == DialogResult.Yes)
            {
                GetMemberInfo(txtSendKey.Text,0);
            }            
            frm.Dispose();
        }

        private async void btnMemberPoint_Click(object sender, EventArgs e)
        {
            new MemberUtil().SetUserPoint(member);
            await ReloadMemberAsync();
        }

        private void txtSendKey_Enter(object sender, EventArgs e)
        {
            //ksKeyBoard1.InputControl = txtSendKey;
        }

        private void password_Click(object sender, EventArgs e)
        {
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择会员，不能修改。");
                return;
            }
            frmModifyPassword frm = new frmModifyPassword(member);
            frm.ShowDialog();
            SetMemberInfo();
            frm.Dispose();            

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                member = null;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "会员读卡出错:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
        }

        private void FrmUserGetInfo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                numPad_OKButtonClick(numPad, "",0, 0);
            }
        }

        private void FrmUserGetInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 118)
            {
                btnRead_Click(null, null);
            }
        }

        private void numPad_OKButtonClick(object sender, string text, int intvalue, double doublevalue)
        {
            if ((member == null) || (member.id == 0) || member.mobile != txtSendKey.Text)
            {
                GetMemberInfo(txtSendKey.Text, 1);
            }
            else
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        private void btnRedeemGoods_Click(object sender, EventArgs e)
        {
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择会员。");
                return;
            }
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isCreditsGoods, 0)) return;
            frmCreditsExchange frm = new frmCreditsExchange(member,(int)GlobalEnumVars.CreditsExchangeType.Goods);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                GetMemberInfo(txtSendKey.Text, 0);
            }
            frm.Dispose();
        }

        private void btnRCreditsPoint_Click(object sender, EventArgs e)
        {
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择会员。");
                return;
            }
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isCreditsIntegral, 0)) return;
            frmCreditsExchange frm = new frmCreditsExchange(member, (int)GlobalEnumVars.CreditsExchangeType.Coupon);
            frm.ShowDialog();
            frm.Dispose();
        }

        private void FrmUserGetInfo_FormClosed(object sender, FormClosedEventArgs e)
        {
            HideWaitForm();
        }

        private async void btnSendCard_ClickAsync(object sender, EventArgs e)
        {
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择会员。");
                return;
            }
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isAddUserInfo, 0)) return;
            FrmUserRegister frmUserRegister = new FrmUserRegister(member, member.mobile);
            if (frmUserRegister.ShowDialog() == DialogResult.OK)
            {
                await ReloadMemberAsync();
            }
            frmUserRegister.Dispose();
        }

        private void FrmUserGetInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            //同个会员，已发生变化，返回确定，解决会员充值后，直接关闭窗口，收银界面不更新的问题
            if ((this.DialogResult == DialogResult.Cancel) && (oldMember != null) && (member != null)
            && (oldMember.id == member.id) && (oldMember.updataTime == member.updataTime))
            {                
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        private void MoreMenu_ValueChanged(object sender, object value)
        {
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择会员。");
                return;
            }
            int tag = CommFunc.ConvertToInt32(value);
            if ((tag == 1) || (tag == 2))
            {
                var frm = new frmMemberCardStatus(member);
                frm.ShowDialog();
                frm.Dispose();
            } else
            if (tag == 3)
            {
                btnSendCard_ClickAsync(null, null);
            }            
        }

        private void btnOprt_Click(object sender, EventArgs e)
        {
            var uIDepositary = new UIMemberMenu(member);
            UIToolStripDropDown MoreMenu = new UIToolStripDropDown(uIDepositary);
            MoreMenu.ValueChanged += MoreMenu_ValueChanged;
            MoreMenu.Show(btnOprt, 0, btnOprt.Height + 5);
        }
    }
}